<template>
	<div v-loading="state.loading" class="layout-padding form-box" style="background: #fff">
		<div class="form-content">
			<el-form ref="inDeliRef" :model="state.form" :rules="state.rules">
				<!-- 基本信息 -->
				<div class="basic-info">
					<div class="info-tab-title">基本信息&nbsp;&nbsp;{{ state.form.inboundCode }}</div>
					<el-row>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="公司主体:" prop="companyId">
								<el-select clearable v-model="state.form.companyId" placeholder="公司主体" @change="changeCompany">
									<el-option v-for="item in state.companyList" :key="item.id" :label="item.name" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="团队:" prop="teamId">
								<el-select clearable v-model="state.form.teamId" placeholder="团队" @change="changeTeam">
									<el-option v-for="item in state.teamList" :key="item.id" :label="item.name" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="入库类型:" prop="busType">
								<el-select clearable v-model="state.form.busType" placeholder="入库类型">
									<el-option v-for="item in state.typeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="入库仓库:" prop="whIdTo">
								<el-cascader
									style="width: 100%"
									:show-all-levels="false"
									v-model="state.form.whIdTo"
									:options="state.whIdToList"
									@change="changeWhIdTo"
									:props="{ value: 'nodeCode', label: 'nodeName' }"
								/>
							</el-form-item>
						</el-col>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="备货区域:" prop="stockupAreaCode">
								<el-select clearable v-model="state.form.stockupAreaCode" placeholder="备货区域" @change="changeStockingArea">
									<el-option v-for="item in state.areaList" :key="item.id" :label="item.stockAreaName" :value="item.stockAreaCode"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="入库日期:" prop="inTimestamp">
								<template #label>
									<div style="display: flex; align-items: center">
										入库日期:
										<el-tooltip effect="dark" content="实际的出库日期：若填写则为填写的时间，若未填写则为系统操作时间" placement="top">
											<el-icon><InfoFilled /></el-icon>
										</el-tooltip>
										<span>:</span>
									</div>
								</template>
								<el-date-picker v-model="state.form.inTimestamp" type="date" placeholder="入库日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
							</el-form-item>
						</el-col>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="物流跟踪号:" prop="logisticsTraceCode">
								<el-input v-model="state.form.logisticsTraceCode" placeholder="物流跟踪号"></el-input>
							</el-form-item>
						</el-col>
						<el-col :sm="12" :md="8" :lg="6">
							<el-form-item label="备注:" prop="remarks">
								<el-input type="textarea" v-model="state.form.remarks" placeholder="" maxlength="500" show-word-limit></el-input>
							</el-form-item>
						</el-col>
						<el-col :sm="24" :md="24" :lg="24">
							<el-form-item label="附件:" prop="value">
								<template #label>
									<div style="display: flex; align-items: center">
										附件:
										<el-tooltip effect="dark" content="单个文件最大不超过5M，附件数量不超过10个" placement="top">
											<el-icon><InfoFilled /></el-icon>
										</el-tooltip>
										<span>:</span>
									</div>
								</template>
								<UploadFile
									:modelValue="state.form.attachmentList"
									:showFileList="true"
									:limit="10"
									position="flex"
									@change="uploadFileContent"
									@remove="removeUploadFile"
									type="simple"
								>
									<template #uploadText>
										<div class="edit-primary flex items-center">
											<el-icon>
												<Upload />
											</el-icon>
											上传附件
										</div>
									</template>
								</UploadFile>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<!-- 产品明细 -->
				<div class="product-info">
					<div class="info-tab-title">产品明细</div>
					<el-button
						class="ml10"
						:disabled="!(state.form.companyId && state.form.teamId && state.form.whIdTo && state.form.stockupAreaCode)"
						plain
						@click="addProductDialogRef?.openDialog()"
						>添加产品</el-button
					>
					<EditTable
						show-summary
						:summary-method="getSummaries"
						:header-cell-style="{ color: '#000', background: '#F5F7FA' }"
						max-height="calc(100vh - 240px)"
						:data="state.form.itemList"
						@addRow="addTr"
						@deleteRow="delTr"
						border
					>
						<template v-slot:editTable>
							<el-table-column type="index" width="80" align="center" label="序号">
								<template v-slot="scope">
									<span>{{ scope.$index + 1 }}</span>
								</template>
							</el-table-column>
							<el-table-column label="图片" prop="picJson" width="80px">
								<template #default="scope">
									<div class="list-image" v-if="scope.row.skuName">
										<ewt-image :url="scope.row.picUrl" style="width: 36px; height: 36px; object-fit: contain; display: block; cursor: pointer" />
										<div class="tag-combination" v-if="scope.row.skuType === '2'">组</div>
									</div>
								</template>
							</el-table-column>
							<el-table-column label="产品名称 / SKU" prop="" min-width="200px">
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div>{{ scope.row.skuName }}</div>
										<div>{{ scope.row.skuCode }}</div>
									</template>
									<el-input
										v-else
										:disabled="!(state.form.companyId && state.form.teamId && state.form.whIdTo && state.form.stockupAreaCode)"
										v-model="scope.row.skuCode"
										placeholder="选择SKU"
										@click="getCurrentClientY($event)"
										@input="openSearchTable(scope.$index, scope.row.skuCode)"
										@focus="openSearchTable(scope.$index, scope.row.skuCode)"
									></el-input>
								</template>
							</el-table-column>
							<el-table-column label="备货平台" prop="stockupPlatformCode" min-width="100px">
								<template #header>
									<span class="table-require"> 备货平台 </span>
								</template>
								<template v-slot="scope">
									<el-form-item :prop="'itemList.' + scope.$index + '.stockupPlatformCode'" :rules="state.rules.stockupPlatformCode">
										<el-select v-if="scope.row.skuName" clearable v-model="scope.row.stockupPlatformCode" placeholder="">
											<el-option
												v-for="item in state.platList"
												:key="item.platformCode"
												:label="item.platformName"
												:value="item.platformCode"
											></el-option>
										</el-select>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column label="FNSKU" prop="fnsku" min-width="100px">
								<template v-slot="scope">
									<el-input v-if="scope.row.skuName" v-model="scope.row.fnsku" placeholder="fnsku"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="供应商" align="center" prop="supplierId" min-width="160px">
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div v-for="(item, ind) in scope.row.productItemList" :key="item.id" class="add-pick">
											<div style="width: 40px; text-align: right">
												<el-icon
													style="margin-right: 6px"
													v-if="scope.row.productItemList.length > 1"
													@click="scope.row.productItemList.splice(ind, 1)"
												>
													<Minus />
												</el-icon>
												<el-icon v-if="ind === scope.row.productItemList.length - 1" @click="scope.row.productItemList.push({})"><Plus /></el-icon>
											</div>
											<el-select class="only-form" v-model="item.supplierId" placeholder="供应商" @change="judgeIsSame(scope.row, item)">
												<el-option
													v-for="supplier in state.supplierList"
													:key="supplier.supplierId"
													:label="supplier.supplierName"
													:value="supplier.supplierId"
													@click="
														item.supplierName = supplier.supplierName;
														item.supplierCode = supplier.supplierCode;
													"
												></el-option>
											</el-select>
										</div>
									</template>
								</template>
							</el-table-column>
							<el-table-column label="产品质量" prop="qualityType" min-width="120px">
								<template #header>
									<span class="table-require">产品质量</span>
								</template>
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div v-for="(item, ind) in scope.row.productItemList" :key="item.id" class="add-pick">
											<el-form-item :prop="'itemList.' + scope.$index + '.productItemList.' + ind + '.qualityType'" :rules="state.rules.qualityType">
												<el-select
													v-model="item.qualityType"
													placeholder="质量"
													@change="
														item.positionId = '';
														item.positionCode = '';
														item.position = [];
														getAvailablePositionObj(scope.row, item);
													"
												>
													<el-option label="良品" value="1"></el-option>
													<el-option label="次品" value="2"></el-option>
													<el-option label="废品" value="3"></el-option>
												</el-select>
											</el-form-item>
										</div>
									</template>
								</template>
							</el-table-column>
							<el-table-column label="是否赠品" prop="giftFlag" min-width="120px">
								<template #header>
									<span class="table-require"> 是否赠品 </span>
								</template>
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div v-for="(item, ind) in scope.row.productItemList" :key="item.id" class="add-pick">
											<el-form-item :prop="'itemList.' + scope.$index + '.productItemList.' + ind + '.giftFlag'" :rules="state.rules.giftFlag">
												<el-select clearable v-model="item.giftFlag" placeholder="是否赠品" @change="judgeIsSame(scope.row, item)">
													<el-option label="是" value="1"></el-option>
													<el-option label="否" value="0"></el-option>
												</el-select>
											</el-form-item>
										</div>
									</template>
								</template>
							</el-table-column>
							<el-table-column
								v-if="state.form.whTypeTo === '1' || state.form.whTypeTo === '2'"
								label="入库库位"
								prop="positionCode"
								min-width="160px"
							>
								<template #header>
									<span class="table-require"> 入库库位 </span>
								</template>
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div v-for="(item, ind) in scope.row.productItemList" :key="item.id" class="add-pick">
											<el-form-item
												:prop="'itemList.' + scope.$index + '.productItemList.' + ind + '.positionCode'"
												:rules="state.rules.positionCode"
											>
												<el-cascader
													v-model="item.position"
													:options="item.seatList"
													placeholder="入库库位"
													:disabled="!item.qualityType"
													filterable
													:props="{ value: 'code', label: 'code', children: 'children' }"
													:show-all-levels="false"
													@focus="getAvailablePositionObj(scope.row, item)"
													@change="changePosition(scope.row, item)"
												/>
											</el-form-item>
										</div>
									</template>
								</template>
							</el-table-column>
							<el-table-column label="入库数量(pcs)" prop="inboundQty" min-width="130px">
								<template #header>
									<span class="table-require">入库数量(pcs)</span>
								</template>
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div v-for="(item, ind) in scope.row.productItemList" :key="item.id" class="add-pick">
											<el-form-item :prop="'itemList.' + scope.$index + '.productItemList.' + ind + '.inboundQty'" :rules="state.rules.inboundQty">
												<el-input
													v-if="scope.row.skuName"
													v-model="item.inboundQty"
													placeholder="入库数量(pcs)"
													oninput="value=value.replace(/^\D*(\d{0,9}(?:)?).*$/g,'$1')"
													@blur="item.inboundQty = Number($event.target.value)"
												></el-input>
											</el-form-item>
										</div>
									</template>
								</template>
							</el-table-column>
							<el-table-column label="采购单价(￥)" prop="purchaseCost" min-width="120px">
								<template #header>
									<span class="table-require"> 采购单价(￥)</span>
								</template>
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div v-for="(item, ind) in scope.row.productItemList" :key="item.id" class="add-pick">
											<el-form-item
												:prop="'itemList.' + scope.$index + '.productItemList.' + ind + '.purchaseCost'"
												:rules="state.rules.purchaseCost"
											>
												<el-input
													v-if="scope.row.skuName"
													v-model="item.purchaseCost"
													placeholder="采购单价(￥)"
													oninput="value=value.replace(/^\D*(\d{0,8}(?:\.\d{0,4})?).*$/g,'$1')"
													@blur="item.purchaseCost = Number($event.target.value)"
												></el-input>
											</el-form-item>
										</div>
									</template>
								</template>
							</el-table-column>
							<el-table-column label="到库成本(￥)" prop="inventoryCost" min-width="120px">
								<template #header>
									<span class="table-require">到库成本(￥)</span>
								</template>
								<template v-slot="scope">
									<template v-if="scope.row.skuName">
										<div v-for="(item, ind) in scope.row.productItemList" :key="item.id" class="add-pick">
											<el-form-item
												:prop="'itemList.' + scope.$index + '.productItemList.' + ind + '.inventoryCost'"
												:rules="state.rules.inventoryCost"
											>
												<el-input
													v-if="scope.row.skuName"
													v-model="item.inventoryCost"
													placeholder="到库成本(￥)"
													oninput="value=value.replace(/^\D*(\d{0,8}(?:\.\d{0,4})?).*$/g,'$1')"
													@blur="item.inventoryCost = Number($event.target.value)"
												></el-input>
											</el-form-item>
										</div>
									</template>
								</template>
							</el-table-column>

							<el-table-column label="明细备注" prop="remarks" min-width="160px">
								<template v-slot="scope">
									<el-input
										v-if="scope.row.skuName"
										type="textarea"
										maxlength="200"
										show-word-limit
										v-model="scope.row.remarks"
										placeholder=""
									></el-input>
								</template>
							</el-table-column>
						</template>
					</EditTable>
				</div>
			</el-form>
		</div>

		<div class="footer-btn">
			<el-button type="" @click="cancelEdit">取消</el-button>
			<el-button class="ml10" type="primary" plain @click="toSaveInOrder(1)">暂存为草稿</el-button>
			<el-button class="ml10" type="primary" v-if="getAuth('wms_inbound_submit')" @click="toSaveInOrder(2)">确认并提交</el-button>
		</div>
		<AddProductDialog
			ref="addProductDialogRef"
			:form="{
				companyId: state.form.companyId,
				teamId: state.form.teamId,
				whIdFrom: state.form.whIdTo,
				stockupAreaCode: state.form.stockupAreaCode,
			}"
			:showProdList="state.form.itemList"
			@selectData="selectData"
			type="inboundDelivery"
		/>
		<searchTable
			:current-search-tr-num="state.currentSearchTrNum"
			:search-value="state.searchValue"
			:currentClientY="state.currentClientY"
			:current-checked-list="state.form.itemList"
			:form="{
				companyId: state.form.companyId,
				teamId: state.form.teamId,
				whIdFrom: state.form.whIdTo,
				stockupAreaCode: state.form.stockupAreaCode,
			}"
			:currentLeft="'400px'"
			type="inboundDelivery"
			@getCurrentSku="getCurrentSku"
		/>
	</div>
</template>

<script lang="ts" setup name="addInDelivery">
import { auth } from '/@/utils/authFunction';
const getAuth = (value: string) => {
	return auth(value);
};
import { ElMessage } from 'element-plus';
import mittBus from '/@/utils/mitt';
import { useRoute } from 'vue-router';
const route = useRoute();
const router = useRouter();
import {
	getCompanyTeamTree,
	getwhTree,
	sysStockArea,
	getPlatformList,
	getDicts,
	getPositionList,
	inboundOrderDetail,
	saveInboundOrder,
	editInboundOrder,
	searchBySupplierName,
} from './api.ts';
const AddProductDialog = defineAsyncComponent(() => import('./components/addProductDialog.vue'));
const searchTable = defineAsyncComponent(() => import('./components/searchTable.vue'));

const state = reactive({
	loading: false,
	form: {
		id: '',
		busType: '',
		inboundOrderType: '0',
		companyId: '',
		companyCode: '',
		companyName: '',
		teamId: '',
		teamCode: '',
		teamName: '',
		whIdTo: '',
		whNameTo: '',
		whCodeTo: '',
		whTypeTo: '',
		stockupAreaCode: '',
		stockupAreaName: '',
		outTimestamp: '',
		statusCode: '',
		attachmentList: [],
		remarks: '',
		itemList: [],
		logisticsTraceCode: '',
	},
	companyList: [],
	teamList: [],
	typeList: [],
	whIdToList: [],
	areaList: [],
	supplierList: [],
	platList: [], //备货平台

	rules: {
		companyId: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
		teamId: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
		busType: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
		whIdTo: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
		stockupAreaCode: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
		outTimestamp: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
		stockPlatformCode: [{ required: true, message: '', trigger: ['blur', 'change'] }],
		qualityType: [{ required: true, message: '', trigger: ['blur', 'change'] }],
		giftFlag: [{ required: true, message: '', trigger: ['blur', 'change'] }],
		inboundQty: [{ required: true, message: '', trigger: ['blur', 'change'] }],
		purchaseCost: [{ required: true, message: '', trigger: ['blur', 'change'] }],
		inTimestamp: [{ required: true, message: '', trigger: ['blur', 'change'] }],
	},
	currentSearchTrNum: null,
	searchValue: '',
	currentClientY: '',
});
const inDeliRef = ref();
const addProductDialogRef = ref();
onMounted(() => {
	state.form.id = route.query.id;
	getCompanyTeamOpt();
	getwhTreeOpt();
	getStockArea();
	getDictsObj();
	getSupplierList();
	getPlatformOpt();
	if (state.form.id) {
		getDetail();
	}
	nextTick(() => {
		document.addEventListener('click', bodyClick);
	});
});
// 获取库区库位级联数据
const getAvailablePositionObj = (row, item, isInit) => {
	if (item?.qualityType) {
		let data = {
			whId: state.form.whIdTo,
			positionType: item.qualityType,
			positionStatus: '1',
			skuId: row.skuId,
		};
		item.seatList = [];
		getPositionList(data).then((res) => {
			res.data.forEach((ele) => {
				let it = {
					code: ele.areaCode,
					id: ele.id,
					children: [],
				};
				ele.positions.forEach((i) => {
					it.children.push({
						code: i.positionCode,
						id: i.positionId,
					});
					if (isInit && item.positionCode === i.positionCode) {
						item.position = [ele.areaCode, i.positionCode];
					}
				});
				item.seatList.push(it);
			});
		});
	}
};
const changePosition = (row, item) => {
	if (item.position?.length > 0) {
		item.positionCode = item.position[1];
		item.seatList.forEach((i) => {
			i.children.find((it) => {
				if (it.code === item.positionCode) {
					item.positionId = it.id;
				}
			});
		});
	}

	judgeIsSame(row, item);
};
const judgeIsSame = (row, item) => {
	let flag = state.form.whTypeTo === '1' || state.form.whTypeTo === '2';
	if (item.supplierId && item.qualityType && item.giftFlag && ((flag && item.positionCode) || (!flag && !item.positionCode))) {
		let arr = row.productItemList.filter((i) => {
			if (i.supplierId && i.qualityType && i.giftFlag && i.inboundQty) {
				return i;
			}
		});
		let setArr = [];
		if (flag) {
			setArr = new Set(
				arr.map(({ supplierId, qualityType, giftFlag, positionCode }) => supplierId + '/' + qualityType + '/' + giftFlag + '/' + positionCode)
			);
		} else {
			setArr = new Set(arr.map(({ supplierId, qualityType, giftFlag }) => supplierId + '/' + qualityType + '/' + giftFlag));
		}

		if (setArr.size !== arr.length) {
			ElMessage({
				message: '同一条明细内，供应商、产品质量、是否赠品、入库库位不可填写一致',
				type: 'error',
			});
		}
	}
};
const toSaveInOrder = async (v) => {
	try {
		let canSaveList = await toValidate();
		if (canSaveList.length > 0) {
			state.form.statusCode = v;
			canSaveList.forEach((ele) => {
				ele.supposeReceiveQty = 0;
				ele.productItemList.map((i) => (ele.supposeReceiveQty += i.inboundQty));
				ele.receivedQtyTotal = ele.supposeReceiveQty;
			});
			state.form.itemList = canSaveList;

			if (!state.form.inboundOrderCode) {
				saveInboundOrder(state.form)
					.then(() => {
						cancelEdit();
						router.push({
							path: '/warehouse/inboundDelivery/inboundDeliveryOrder/index',
						});
						state.loading = false;
					})
					.catch((res) => {
						ElMessage({
							message: res.msg,
							type: 'error',
						});
						state.loading = false;
					});
			} else {
				editInboundOrder(state.form)
					.then(() => {
						cancelEdit();
						router.push({
							path: '/warehouse/inboundDelivery/inboundDeliveryOrder/index',
						});
						state.loading = false;
					})
					.catch((res) => {
						ElMessage({
							message: res.msg,
							type: 'error',
						});
						state.loading = false;
					});
			}
		}
	} catch (error) {
		ElMessage({
			message: error.msg,
			type: 'error',
		});
	}
};

const toValidate = () => {
	return new Promise((resolve, reject) => {
		inDeliRef?.value.validate((valid) => {
			if (!valid) {
				reject({ msg: '数据未填写完整' });
			} else {
				let currentList = state.form.itemList.filter((item) => item.skuCode);
				if (currentList.length === 0) {
					reject({ msg: '请选择至少一条产品明细' });
				} else {
					currentList.forEach((item) => {
						const setArr = new Set(
							item.productItemList.map(
								({ supplierId, qualityType, giftFlag, positionCode }) => supplierId + '/' + qualityType + '/' + giftFlag + '/' + positionCode
							)
						);

						if (setArr?.size !== item.productItemList.length) {
							reject({ msg: '同一条明细内，供应商、产品质量、是否赠品、入库库位不可填写一致' });
						} else {
							resolve(currentList);
						}
					});
				}
			}
		});
	});
};
const getDictsObj = async () => {
	const { data } = await getDicts('inbound_bus_type ');
	let arr = ['3', '4', '5', '6'];
	state.typeList = data.filter((item) => {
		return arr.includes(item.value);
	});
};
// 获取详情
const getDetail = async () => {
	try {
		state.loading = true;
		const { data } = await inboundOrderDetail(state.form.id);
		state.form = data;
		state.companyList.forEach((item) => {
			if (data.companyId === item.id) {
				state.teamList = item.subList;
			}
		});
		if (!state.form.attachmentList) {
			state.form.attachmentList = [];
		}

		if (state.form.whTypeTo === '1' || state.form.whTypeTo === '2') {
			state.form.itemList.forEach((item) => {
				item.productItemList.forEach((pro) => {
					getAvailablePositionObj(item, pro, true);
				});
			});
		}
		state.loading = false;
		console.log(state.form);
	} catch (error) {
		ElMessage({
			message: error.msg,
			type: 'error',
		});
	}
};
// 获取备货平台
const getPlatformOpt = async () => {
	const { data } = await getPlatformList();
	state.platList = data;
};
// 获取供应商
const getSupplierList = (value) => {
	searchBySupplierName({ supplierName: value, openStatus: '1', approvalStatus: '2' }).then((res) => {
		state.supplierList = res.data;
	});
};
// 获取公司主体
const getCompanyTeamOpt = async () => {
	const { data } = await getCompanyTeamTree();
	state.companyList = data;
};
// 获取团队
const changeCompany = (v) => {
	state.form.itemList = [];
	state.teamList = [];
	state.form.teamId = '';
	state.form.teamCode = '';
	state.form.teamName = '';
	state.companyList.forEach((item) => {
		if (v === item.id) {
			state.form.companyName = item.name;
			state.form.companyCode = item.code;
			state.teamList = item.subList;
		}
	});
};
// 获取仓库树形结构
const getwhTreeOpt = async () => {
	const { data: whIdToList } = await getwhTree({ whInOrOut: '1', whStatus: '1' });
	state.whIdToList = whIdToList;
};
// 备货区域
const getStockArea = async () => {
	const { data } = await sysStockArea();
	state.areaList = data;
};
// 团队选择后
const changeTeam = (v) => {
	state.form.itemList = [];
	state.teamList.forEach((item) => {
		if (v === item.id) {
			state.form.teamName = item.name;
			state.form.teamCode = item.code;
		}
	});
};
// 仓选择后
const changeWhIdTo = (v) => {
	state.form.itemList = [];
	if (!v) {
		state.form.whIdTo = '';
		state.form.whCodeTo = '';
		state.form.whNameTo = '';
		state.form.whTypeTo = '';
	} else {
		state.form.whIdTo = v.at(-1);
		state.form.whTypeTo = v[0];
		changeWhsName('', state.whIdToList, v.at(-1), 'whNameTo', 'whCodeTo');
	}
};
const changeWhsName = (parentName, children, v, key1, key2) => {
	children.forEach((it) => {
		it.parentName = parentName ? parentName + '/' + it.nodeName : it.nodeName;
		if (it.children) {
			changeWhsName(it.parentName, it.children, v, key1, key2);
		} else {
			if (it.nodeCode === v) {
				state.form[key1] = parentName ? parentName + '/' + it.nodeName : it.nodeName;
				state.form[key2] = it.whCode;
				return false;
			}
		}
	});
};
// 备货区域选择后
const changeStockingArea = (v) => {
	state.form.itemList = [];
	state.areaList.forEach((item) => {
		if (v === item.stockAreaCode) {
			state.form.stockupAreaName = item.stockAreaName;
		}
	});
};
const uploadFileContent = (data: any) => {
	const { fileName, fileSpace, fileUrl } = data;
	state.form.attachmentList.push({
		fileName,
		fileSpace,
		fileUrl,
		fileId: '',
	});
};
const removeUploadFile = (data: any) => {
	const index = state.form.attachmentList.findIndex((item) => item?.fileUrl === data.url);
	state.form.attachmentList.splice(index, 1);
};
const getSummaries = (param: SummaryMethodProps) => {
	const { columns, data } = param;
	const sums: string[] = [];
	columns.forEach((column, index) => {
		const values = data.map((item) => Number(item[column.property]));
		if (!values.every((value) => Number.isNaN(value))) {
			sums[index] = `${values.reduce((prev, curr) => {
				let value = Number(curr);
				if (!Number.isNaN(value)) {
					return prev + curr;
				} else {
					return prev;
				}
			}, 0)}`;
		} else {
			sums[index] = '';
		}
	});
	// 单独处理
	sums[0] = '合计';
	for (var i = 1; i <= 11; i++) {
		sums[i] = '';
	}
	let num = 0;
	sums[9] = 0;
	data.forEach((item) => {
		if (item.skuCode) {
			num++;
		}
		if (item.productItemList?.length > 0) {
			item.productItemList.forEach((i) => {
				if (i.inboundQty) {
					sums[9] = Number(sums[9] + Number(i.inboundQty));
				}
			});
		}
	});
	sums[2] = num + '个产品';
	return sums;
};
const addTr = () => {
	state.form.itemList.push({});
};
const delTr = (trInd: any) => {
	state.form.itemList.splice(trInd.$index, 1);
};
// 选中的数据
const selectData = (data) => {
	data.map((it) => {
		it.skuCode = it.sku;
		it.skuAttrs = JSON.stringify(it.attrValueList);
		it.singleBoxWeight = it.oneBoxWeight;
		it.boxNum = 0;
		it.outboundQty = 0;
		it.remarks = '';
		it.qualityType = '1';
		it.stockupPlatformCode = it.stockPlatformCode;
		it.stockupPlatformName = it.stockPlatformName;
		it.stockupAreaCode = state.form.stockupAreaCode;
		it.stockupAreaName = state.form.stockupAreaName;
		it.productItemList = [{}];
	});
	state.form.itemList = data;
};
// 列表搜索框处理
const getCurrentClientY = (event) => {
	state.currentClientY = event.clientY - 140 + 'px';
	if (event.clientY > document.body.clientHeight - 590) {
		state.currentClientY = document.body.clientHeight - 690 + 'px';
	}
};
const openSearchTable = (trIndex, searchValue) => {
	state.currentSearchTrNum = trIndex + 1;
	state.searchValue = searchValue;
};
const bodyClick = (e) => {
	const tableBox = document.querySelector('.search-table-box');
	const tablePagination = document.querySelector('.search-table-pagination');
	if (tableBox && tablePagination && !tableBox.contains(e.target) && e.target.nodeName !== 'INPUT' && !tablePagination.contains(e.target)) {
		state.currentSearchTrNum = null;
	}
};
const getCurrentSku = (row: any, trNum: any) => {
	state.form.itemList[trNum - 1] = row;
	state.form.itemList[trNum - 1].skuCode = row.sku;
	state.form.itemList[trNum - 1].skuAttrs = JSON.stringify(row.attrValueList);
	state.form.itemList[trNum - 1].singleBoxWeight = row.oneBoxWeight;
	state.form.itemList[trNum - 1].boxNum = 0;
	state.form.itemList[trNum - 1].outboundQty = 0;
	state.form.itemList[trNum - 1].remarks = '';
	state.form.itemList[trNum - 1].qualityType = '1';
	state.form.itemList[trNum - 1].stockupPlatformCode = row.stockPlatformCode;
	state.form.itemList[trNum - 1].stockupPlatformName = row.stockPlatformName;
	state.form.itemList[trNum - 1].stockupAreaCode = state.form.stockupAreaCode;
	state.form.itemList[trNum - 1].stockupAreaName = state.form.stockupAreaName;
	state.form.itemList[trNum - 1].productItemList = [{}];

	state.currentSearchTrNum = null;
};
const cancelEdit = () => {
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
};
</script>

<style lang="scss" scoped>
.el-col {
	margin-bottom: 20px;
}
.table-require::before {
	content: '*';
	color: #e52e2e;
	margin-right: 4px;
}
.form-box {
	position: relative;
}
.form-content {
	height: calc(100% - 66px);
	overflow: auto;
}
.footer-btn {
	position: absolute;
	bottom: 16px;
	left: 0;
	right: 0;
	text-align: center;
}
.info-tab-title {
	position: relative;
	height: 24px;
	font-size: 14px;
	line-height: 24px;
	font-weight: 600;
	color: #0b1019;
	padding-left: 10px;
	margin-bottom: 20px;
	display: flex;
	&:before {
		content: ' ';
		display: inline-block;
		position: absolute;
		top: 5px;
		left: 0;
		height: 14px;
		width: 2px;
		background: #005bf5;
	}
}
.non-pic {
	background: rgba(11, 16, 25, 0.05);
	border: 1px solid rgba(0, 0, 0, 0.03);
	color: rgba(11, 16, 25, 0.12);
	border-radius: 2px;
	display: flex;
	-webkit-box-pack: center;
	-ms-flex-pack: center;
	justify-content: center;
	-webkit-box-align: center;
	-ms-flex-align: center;
	align-items: center;
	width: 36px;
	height: 36px;
	line-height: 36px;
	text-align: center;
}
.el-col :deep(.el-form-item__label) {
	width: 120px !important;
}
.add-pick {
	display: flex;
	align-items: center;
	gap: 6px;
	margin: 6px 0;
}
.add-pick .only-form {
	width: calc(100% - 40px) !important;
}
.add-pick i {
	cursor: pointer;
}
</style>